package com.tarena.sentinel.demo02.datasource;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.FileRefreshableDataSource;
import com.alibaba.csp.sentinel.init.InitFunc;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.util.List;

/**
 * 读取本地一个flowRules.json文件
 * 转化成List<FlowRule> 对象 交给sentinel使用
 */
@Slf4j
public class FileDatasource implements InitFunc {
    @Override
    public void init() throws Exception {
        //1. 找到文本 flowRules.json 路径
        ClassLoader classLoader = FileDatasource.class.getClassLoader();
        URL resource = classLoader.getResource("flowRules.json");
        //拿到文件flowRules.json路径名称
        String filePath=resource.getPath();
        log.info("当前文件的全路径:"+filePath);
        //2. 给sentinel加载
        FileRefreshableDataSource dataSource=
                new FileRefreshableDataSource(filePath, new Converter() {
                    @Override
                    public Object convert(Object json) {
                        //json就是字符串文本
                        String str=(String)json;
                        System.out.println("读取到的文本信息:"+str);
                        //转化结果 编程List<FlowRule> 数组对象 FAST JSON
                        List<FlowRule> flowRules = JSON.parseArray(str, FlowRule.class);
                        return flowRules;
                    }
                });
        //sentinel的管理工具 加载数据源的属性
        FlowRuleManager.register2Property(dataSource.getProperty());
        System.out.println("sentinel规则加载完毕");
    }
}
